<template>
  <div class="app-container">
    <el-row :gutter="18">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-add"
          size="large"
          @click="handleAdd"
          >新建关联</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="large"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
    </el-row>
    <el-table
      class="user-table"
      v-loading="loading"
      :data="goodsSpuList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" prop="id" width="120" align="center" />
      <el-table-column
        label="商品名称"
        prop="goodsName"
        :show-overflow-tooltip="true"
        width="150"
        align="center"
      />
      <el-table-column label="属性" prop="attrName" width="120" align="center">
      </el-table-column>
      <el-table-column
        label="属性值"
        prop="attrValue"
        width="200"
        align="center"
      />
      <el-table-column label="状态" prop="status" width="200" align="center">
        <template slot-scope="{ row }">
          <el-tag :type="row.status === 0 ? 'primary' : 'danger'">{{
            row.status == 0 ? "正常" : "禁用"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="large"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >移除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-row :span="24" style="margin-top: 20px">
      <el-col :span="24" :offset="15">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="postData.pageNo"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="postData.pageSize"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        >
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog
      title="新建商品关联属性"
      :visible.sync="open"
      width="500px"
      height="600px"
      lock-scroll
      top="15vh"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        size="mini"
      >
        <el-form-item label="商品名称">
          <el-input v-model="goodsName" :disabled="true" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsId" hidden>
          <el-input v-model="form.goodsId" :disabled="true" />
        </el-form-item>
        <el-form-item label="属性">
          <el-select
            v-model="attrId"
            placeholder="请选择属性"
            clearable
            style="width: 240px"
            @change="changeAttrValuesList(attrId)"
          >
            <el-option
              v-for="(item, index) in attrList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="属性值" prop="attrValueId">
          <el-select
            v-model="form.attrValuesId"
            placeholder="请选择属性值"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="(item, index) in attrValueList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "GoodsRelation",
  data() {
    return {
      loading: false,
      goodsSpuList: [],
      SpuList: [],
      totalCount: 0,
      postData: {
        goodsId: null,
        pageSize: 5,
        pageNo: 1,
      },
      attrList: [], //属性列表
      attrValueList: [], //属性值列表
      attrId: null, //选中的属性id
      open: false, //是否打开添加或修改对话框
      // 非多个禁用
      multiple: true,
      ids: [], //选中的用户id集合
      form: {
        goodsId: Number(this.$route.query.id), //商品id
        attrValuesId: null, //属性值id
        status: 1, //状态 0正常 1禁用
      },
      goodsName: "", //商品名称
      rules: {
        attrValuesId: [
          { required: true, message: "请选择属性值", trigger: "change" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
    };
  },
  created() {
    this.postData.goodsId = this.$route.query.id;
    this.goodsName = this.$route.query.goodsName;
    this.getList();
    this.getAttrList();
    this.getAttrValuesList();
    this.getAll(this.postData.goodsId);
  },
  methods: {
    async getList() {
      this.loading = true;
      try {
        const res = await this.$axios("/api/goods/attr/values/list", {
          params: this.postData,
        });
        if (res.data.code === 200) {
          this.totalCount = res.data.data.totalCount;
          this.goodsSpuList = res.data.data.data;
        }
      } catch (error) {
        this.$message.error("获取商品关联属性失败");
      } finally {
        this.loading = false;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          //添加
          const res = await this.$axios.post(
            "/api/goods/attr/values/add",
            this.form
          );
          if (res.data.code === 200) {
            this.$message.success("添加成功");
            this.open = false;
            this.getList();
            this.getAll(this.postData.goodsId);
          } else {
            this.$message.error(res.data.msg);
          }
        }
        this.form = {
          goodsId: Number(this.$route.query.id), //商品id
          attrValuesId: null, //属性值id
          status: 1, //状态 0正常 1禁用
        };
        this.attrId = null;
      });
    },
    //取消按钮
    cancel() {
      this.open = false;
      this.$refs["form"].resetFields();
    },
    //获取属性列表
    async getAttrList() {
      const res = await this.$axios.get("/api/attr/all");
      if (res.data.code === 200) {
        this.attrList = res.data.data;
      }
    },

    async changeAttrValuesList(attrId) {
      //刷新
      await this.getAll(this.postData.goodsId);
      await this.getAttrValuesList();
      this.attrValueList = this.attrValueList.filter(
        (item) => item.attrId === attrId
      );
      this.attrValueList = this.attrValueList
        .filter(
          (item) => !this.SpuList.some((spu) => spu.attrValuesId === item.id)
        )
        .map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
    },

    //获取属性值列表
    async getAttrValuesList() {
      const res = await this.$axios.get("/api/attr/values/all");
      if (res.data.code === 200) {
        this.attrValueList = res.data.data;
      }
    },

    //获取全部商品关联属性
    async getAll(goodsId) {
      const res = await this.$axios.get(
        "/api/goods/attr/values/all?goodsId=" + goodsId
      );
      if (res.data.code === 200) {
        this.SpuList = res.data.data;
      }
    },

    handleDelete(row) {
      const id = [row.id] || this.ids;
      this.$confirm(`是否删除编号为${id}的数据项`, "提示", {
        type: "warning",
      })
        .then(async () => {
          const res = await this.$axios.post("/api/goods/attr/values/del", id);
          if (res.data.code === 200) {
            this.$message.success("删除成功");
            this.getList();
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    handleAdd() {
      this.open = true;
    },
    //当页面变化时的事件
    handleCurrentChange(pageNo) {
      //修改当前页码
      this.postData.pageNo = pageNo;
      //执行查询
      this.getList();
    },
    //每当页数量下拉框选项切换变化时的事件
    handleSizeChange(pageSize) {
      //修改查询条件中的的每页数量
      this.postData.pageSize = pageSize;
      //执行查询
      this.getList();
    },
    //多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
  },
};
</script>

<style>
.user-table {
  margin-top: 20px;
}
.app-container {
  padding: 20px;
}
</style>
